package cn.tnar.yunpark.careyes;

import cn.tnar.yunpark.util.ByteTool;
import io.netty.buffer.ByteBuf;

/**
 * author : CaineZhu
 * date   : 2017/12/22 ${time}
 * desc   : class desc
 */
public class BCCTool {

    public static byte bccCalc(byte[] data, int offSet, int len) {
        byte temp = (byte) 0x00;
        for (int i = offSet; i < offSet + len; i++) {
            temp ^= data[i];
        }
        return temp;
    }

    public static byte bccCalc(ByteBuf buf) {
        byte[] data = new byte[buf.readableBytes()];
        buf.getBytes(0, data);
        return bccCalc(data, 0, data.length);
    }

    public static boolean crcValidation(ByteBuf buf) {
        byte[] source = new byte[buf.readableBytes()];
        buf.getBytes(0, source);
        int len = source.length;
        System.out.println("crcValidation len: "+len+"data:"+ ByteTool.bytes2String(source));
        byte sourceCrc = source[len - 3];
        byte newCrc = bccCalc(source,0,len - 3);
        System.out.println("sourceCrc:"+ ByteTool.bytes2StringWithOutBlank(sourceCrc)+" newCrc:"+ByteTool.bytes2StringWithOutBlank(newCrc));
        return sourceCrc == newCrc;
    }
}
